package server

import (
	"3-19yk/common/models/mysql"
	"3-19yk/common/proto/user"
	"3-19yk/pkg"
	"fmt"
	jwt "github.com/golangblogs/gojwt"
	"gorm.io/gorm"
	"log"
)

func Login(req *user.LoginReq) (*user.LoginResp, error) {
	m := mysql.User{}
	getUser, err := m.GetUser(req.Phone)
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	if getUser.Phone == "" {
		m2 := mysql.User{
			Model:    gorm.Model{},
			Phone:    req.Phone,
			Password: req.Password,
		}
		err := m.Create(&m2)
		if err != nil {
			return nil, fmt.Errorf("注册失败")
		}
	}
	if getUser.Password != req.Password {
		return nil, fmt.Errorf("密码错误")
	}
	claims := jwt.CustomClaims{ID: getUser.ID}
	token, err := jwt.NewJWT("2209a").CreateToken(claims)
	if err != nil {
		return nil, fmt.Errorf("token生成失败")
	}
	return &user.LoginResp{Greet: token}, nil
}

func RealName(req *user.RealNameReq) (*user.RealNameResp, error) {
	name := mysql.RealName{}
	realName, err := name.GetRealName(int(name.ID))
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	if realName.ID > 0 {
		log.Println("用户已实名认证")
		return nil, err
	}
	if !pkg.RealName(req.IdCard, req.RealNames) {
		return nil, fmt.Errorf("第三方调用失败")
	}
	m := mysql.RealName{
		Model:     gorm.Model{},
		UserId:    int(req.UserId),
		RealNames: req.RealNames,
		IdCard:    req.IdCard,
	}
	err = realName.Create(&m)
	if err != nil {
		return nil, fmt.Errorf("实名认证失败")
	}
	return &user.RealNameResp{Success: "实名认证成功"}, nil
}
